Ext.namespace('SpeciesObservation')

SpeciesObservation.Users=function(config){
	var userStore = new Ext.data.JsonStore({
			url: Config.baseUrl + 'resources/api/api.php'
		,	baseParams: { 
				cmd: 'getUsers' 
			}
		,	root: 'data'
		,	fields: [
					{name: 'user_id', mapping: 'user_id'}
				,	{name: 'name', mapping: 'name'}	
				,	{name: 'email', mapping: 'email'}
				,	{name: 'permission', mapping: 'permission'}
			]			
		,	remoteSort: false
		,	autoLoad: true
	});
	
	var sm =  new Ext.grid.RowSelectionModel({
		singleSelect: true
	,  	listeners: {
			rowselect: function(sm, row, rec) {
				this.getForm().loadRecord(rec)
			}
		,	scope: this	
		}
	});
	
	var cm = new Ext.grid.ColumnModel([{
		id: 'userName'
	,	header: "User Name"
	, 	width: 100
	, 	sortable: true
	, 	dataIndex: 'name'
	}, {
		header: "Email"
	, 	width: 120
	, 	sortable: true
	, 	dataIndex: 'email'
	}, {
		header: "Permission"
	, 	width: 120
	, 	sortable: true
	, 	dataIndex: 'permission'
	//,	renderer: this.getPermission
    }]);
	
	this.userGrid = new Ext.grid.GridPanel({
		store: userStore
	,	cm: cm
    ,   sm: sm
    ,	autoExpandColumn: 'userName'
    ,	height: 350
    ,	title:'Users List'
	,	iconCls: 'icon_group'
    ,	border: true
	,	autoScroll: true
	});
	Ext.apply(Ext.form.VTypes, {
	   password: function(value, field){
		  if (field.initialPasswordField)
		  {
			 var pwd = Ext.getCmp(field.initialPasswordField);
			 this.passwordText = 'Confirmation does not match your intial password entry.';
			 return (value == pwd.getValue());
		  }
	 
		  this.passwordText = 'Passwords must be at least 5 characters.';
//		  this.passwordText = 'Passwords must be at least 5 characters, containing either a number, or a valid special character (!@#$%^&*()-_=+)';
	 
//		  var hasSpecial = value.match(/[0-9!@#\$%\^&\*\(\)\-_=\+]+/i);
		  var hasLength = (value.length >= 5);
	 
		  return (hasLength);
//		  return (hasSpecial && hasLength);
	   },
	   passwordText: 'Passwords must be at least 5 characters, containing either a number, or a valid special character (!@#$%^&*()-_=+)',
	});
	
	Ext.apply(this, config, {
		frame: true
    ,	labelAlign: 'left'
    ,   title: 'Users'
    ,   bodyStyle:'padding:5px'
    ,   width: 750
    ,   layout: 'column'
    ,	items: [{
				columnWidth: 0.60
            ,	layout: 'fit'
			,	items: this.userGrid
			},{
				columnWidth: 0.4
			,	xtype: 'fieldset'
            ,	labelWidth: 90
            ,	title:'User details'
			,	iconCls: 'icon_user'
            ,	defaults: {width: 140, border:false, anchor: '100%'}
            ,	defaultType: 'textfield'
            ,	autoHeight: true
            ,	bodyStyle: Ext.isIE ? 'padding:0 0 5px 15px;' : 'padding:10px 15px;'
            ,	border: false
            ,	style: {
					"margin-left": "10px"
                ,	"margin-right": Ext.isIE6 ? (Ext.isStrict ? "-10px" : "-13px") : "0" 
				}
            ,	items: [{
					fieldLabel: 'User Name'
                ,	name: 'name'
				,	allowBlank: false
				},{
                	fieldLabel: 'Email'
                ,	name: 'email'
				,	allowBlank: false
				}, {
					xtype: 'radiogroup'
				,	columns: 1
				,	fieldLabel: 'Permission'
				,	allowBlank: false
				,	vtype: 'email'
				,	items: [{
						name: 'permission'
					,	inputValue: 'ADMIN'
					,	boxLabel: 'ADMIN'
					}, {
						name: 'permission'
					,	inputValue: 'MANAGER'
					,	boxLabel: 'MANAGER'
					}, {
						name: 'permission'
					,	inputValue: 'DATAENTRY'
					,	boxLabel: 'DATAENTRY'
					}]
				},{
					fieldLabel: 'Password'
				,	name: 'password'
				,	inputType: 'password'
				,	vtype: 'password'
				,	maxLength: 64
			}]
		}]
	,	bbar: [{
				text: 'Clear'
			,	scope: this
			,	handler: function(){
					this.getForm().reset();
					this.userGrid.getSelectionModel().clearSelections();
				}	
			},'->',{
				text: 'Add'
			,	scope: this
			,	iconCls: 'icon_addUser'
			,	handler: this.addUser
			},{
				text: 'Update'
			,	scope: this
			,	iconCls: 'icon_updateUser'
			,	handler: this.updateUser
			},{
				text: 'Delete'
			,	scope: this
			,	iconCls: 'icon_deleteUser'
			,	handler: this.deleteUser
			}]	
	});
	
	SpeciesObservation.Users.superclass.constructor.call(this, config)

};

Ext.extend(SpeciesObservation.Users, Ext.form.FormPanel, {
	getPermission: function(value){
		if (value == 'ADMIN' ) return "ADMIN"
        if (value == 'MANAGER' ) return "MANAGER"
        if (value == 'DATAENTRY' ) return "DATAENTRY"
	}
,	addUser: function(){
		var val = this.getForm().getValues();
		if(Ext.isEmpty(val.password) || !this.getForm().isValid()){
			SpeciesObservation.Notice.msg('Notice', 'Please enter valid values.');
		}else{
			var params = {};
			Ext.apply(params, {
				cmd: 'addUser'
			},val);
			var msg = "User added successfully."
			this.requestUser(params, msg);
		}	
	}	
,	updateUser: function(){
		var selected = this.userGrid.getSelectionModel().getSelected();
		if(Ext.isEmpty(selected)){
			SpeciesObservation.Notice.msg('Notice', 'Please select user.');
		}else {
			var val = this.getForm().getValues();
			var params = {};
			Ext.apply(params, {
				cmd:'updateUser'
			,	user_id: selected.data.user_id
			},val);
			if(this.getForm().isValid()){
				var msg = "User updated successfully."
				this.requestUser(params, msg);
			}else {
				SpeciesObservation.Notice.msg('Notice','Please enter valid values.');
			}
		}
	}
,	deleteUser: function(){
		var selected = this.userGrid.getSelectionModel().getSelected();
		if(Ext.isEmpty(selected)){
			SpeciesObservation.Notice.msg('Notice', 'Please select user.');
		}else {
			Ext.Msg.confirm('Confirm', 'Are you sure to delete user?', function(btn){
				if(btn == 'yes'){
					var params = {
						cmd: 'deleteUser'
					,	user_id: selected.data.user_id
					}
					var msg = "User deleted successfully."
					this.requestUser(params, msg);
				}
			}, this);
		}
	}
,	requestUser: function(params, msg){
		var myMask = new Ext.LoadMask(this.userGrid.el.dom, {msg: 'Please wait...'});
		myMask.show();
		Ext.Ajax.request({
				url: Config.baseUrl + 'resources/api/api.php'
			,	method: 'POST'
			,	scope: this
			,	params: params
			,	success: function(responseObject){
					var o = Ext.decode(responseObject.responseText);
					if(o.success){
						SpeciesObservation.Notice.msg("Success", msg);
						this.userGrid.getStore().reload();
						myMask.hide();
						this.getForm().reset();
					}else{
						SpeciesObservation.Notice.msg("Notice", o.error);
						myMask.hide();
					}	
				}
			,	failure: function(res){
					SpeciesObservation.Notice.msg("Error", "Fatal Error.");
					myMask.hide();
				}
		}, this);
	}
})